<script setup lang="ts">
import { ref, onMounted } from "vue";
import { invoke } from "@tauri-apps/api/core";
import { homeDir } from '@tauri-apps/api/path';

interface FileEntry {
  name: string;
  is_directory: boolean;
}

const currentPath = ref<string>("");
const directoryContents = ref<FileEntry[]>([]);
const errorMessage = ref<string | null>(null);
const pathInput = ref<string>("");
const newFolderName = ref<string>("");

// Get file icon based on extension and type
function getFileIcon(entry: FileEntry): string {
  if (entry.is_directory) return '📁';
  
  const ext = entry.name.split('.').pop()?.toLowerCase();
  const iconMap: { [key: string]: string } = {
    'txt': '📝', 'md': '📝', 'doc': '📝', 'docx': '📝',
    'pdf': '📕', 'epub': '📖',
    'jpg': '🖼️', 'jpeg': '🖼️', 'png': '🖼️', 'gif': '🖼️', 'bmp': '🖼️', 'svg': '🖼️',
    'mp4': '🎬', 'avi': '🎬', 'mov': '🎬', 'mkv': '🎬',
    'mp3': '🎵', 'wav': '🎵', 'flac': '🎵', 'aac': '🎵',
    'zip': '🗜️', 'rar': '🗜️', '7z': '🗜️', 'tar': '🗜️',
    'js': '📜', 'ts': '📜', 'vue': '📜', 'html': '📜', 'css': '📜',
    'exe': '⚙️', 'msi': '⚙️', 'app': '⚙️'
  };
  
  return iconMap[ext || ''] || '📄';
}

function getFileType(entry: FileEntry): string {
  if (entry.is_directory) return '文件夹';
  
  const ext = entry.name.split('.').pop()?.toLowerCase();
  if (!ext) return '文件';
  
  const typeMap: { [key: string]: string } = {
    'txt': '文本文件', 'md': 'Markdown', 'doc': 'Word文档', 'docx': 'Word文档',
    'pdf': 'PDF文档', 'epub': '电子书',
    'jpg': '图片', 'jpeg': '图片', 'png': '图片', 'gif': '动图', 'bmp': '图片', 'svg': '矢量图',
    'mp4': '视频', 'avi': '视频', 'mov': '视频', 'mkv': '视频',
    'mp3': '音频', 'wav': '音频', 'flac': '音频', 'aac': '音频',
    'zip': '压缩包', 'rar': '压缩包', '7z': '压缩包', 'tar': '压缩包',
    'js': 'JavaScript', 'ts': 'TypeScript', 'vue': 'Vue组件', 'html': 'HTML', 'css': '样式表',
    'exe': '可执行文件', 'msi': '安装包', 'app': '应用程序'
  };
  
  return typeMap[ext] || ext.toUpperCase() + '文件';
}

function getBreadcrumb(): string {
  if (!currentPath.value) return '';
  const parts = currentPath.value.replace(/\\/g, '/').split('/').filter(Boolean);
  return parts.length > 2 ? `.../${parts.slice(-2).join('/')}` : currentPath.value;
}

async function fetchDirectoryContents(pathToLoad?: string) {
  const targetPath = pathToLoad || pathInput.value || currentPath.value;
  if (!targetPath) {
    errorMessage.value = "路径不能为空";
    return;
  }
  try {
    errorMessage.value = null;
    const result = await invoke<FileEntry[]>("list_directory_contents", { path: targetPath });
    directoryContents.value = result;
    currentPath.value = targetPath;
    pathInput.value = targetPath;
  } catch (err: any) {
    console.error("Error fetching directory contents:", err);
    directoryContents.value = [];
    errorMessage.value = `无法加载目录内容: ${err.toString()}`;
  }
}

async function navigateTo(entry: FileEntry) {
  if (entry.is_directory) {
    const newPath = currentPath.value.endsWith('/') || currentPath.value.endsWith('\\')
      ? `${currentPath.value}${entry.name}`
      : `${currentPath.value}/${entry.name}`;
    pathInput.value = newPath;
    await fetchDirectoryContents(newPath);
  } else {
    console.log("Clicked on file:", entry.name);
  }
}

async function goUp() {
  if (!currentPath.value) return;

  let path = currentPath.value.replace(/\\/g, '/');

  if (path.match(/^[a-zA-Z]:\/$/) || path === "/") {
     console.log("Already at root or drive root.");
     return; 
  }

  const lastSlashIndex = path.lastIndexOf('/');
  if (lastSlashIndex > 0) {
    let parentPath = path.substring(0, lastSlashIndex);
    if (parentPath.match(/^[a-zA-Z]:$/) && path.startsWith(parentPath + "/")) {
        parentPath += "/";
    }
    pathInput.value = parentPath;
    await fetchDirectoryContents(parentPath);
  } else if (lastSlashIndex === 0 && path.length > 1) {
    pathInput.value = "/";
    await fetchDirectoryContents("/");
  }
}

onMounted(async () => {
  try {
    const dir = await homeDir();
    currentPath.value = dir;
    pathInput.value = dir;
    await fetchDirectoryContents();
  } catch (e) {
    console.error("Failed to get home directory:", e);
    const fallbackPath = "C:\\";
    currentPath.value = fallbackPath;
    pathInput.value = fallbackPath;
    await fetchDirectoryContents();
  }
});

function handlePathSubmit() {
  fetchDirectoryContents(pathInput.value);
}

async function handleCreateFolder() {
  if (!newFolderName.value.trim()) {
    errorMessage.value = "文件夹名称不能为空";
    return;
  }
  if (!currentPath.value) {
    errorMessage.value = "当前路径无效，无法创建文件夹";
    return;
  }

  const separator = currentPath.value.endsWith('/') || currentPath.value.endsWith('\\') ? '' : '/';
  const fullPath = `${currentPath.value}${separator}${newFolderName.value.trim()}`;

  try {
    errorMessage.value = null;
    await invoke("create_folder", { path: fullPath });
    newFolderName.value = "";
    await fetchDirectoryContents(currentPath.value);
  } catch (err: any) {
    console.error("Error creating folder:", err);
    errorMessage.value = `创建文件夹失败: ${err.toString()}`;
  }
}
</script>

<template>
  <main class="container">
    <!-- Header Section -->
    <header class="app-header">
      <div class="header-content">
        <div class="logo-section">
          <div class="logo-icon">🗂️</div>
          <h1>智效文件管理器</h1>
        </div>
        <div class="header-actions">
          <div class="breadcrumb">{{ getBreadcrumb() }}</div>
        </div>
      </div>
    </header>

    <!-- Navigation Bar -->
    <nav class="nav-bar">
      <form class="path-form" @submit.prevent="handlePathSubmit">
        <button type="button" class="nav-btn up-btn" @click="goUp" :disabled="!currentPath || !!currentPath.match(/^[a-zA-Z]:\/$/) || currentPath === '/'">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
            <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/>
          </svg>
          上一级
        </button>
        <div class="path-input-container">
          <input id="path-input" v-model="pathInput" placeholder="输入路径..." />
          <button type="submit" class="nav-btn browse-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
            </svg>
            浏览
          </button>
        </div>
      </form>

      <form class="create-form" @submit.prevent="handleCreateFolder">
        <div class="create-input-container">
          <input id="new-folder-input" v-model="newFolderName" placeholder="新建文件夹..." />
          <button type="submit" class="nav-btn create-btn">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
              <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
            </svg>
            创建
          </button>
        </div>
      </form>
    </nav>

    <!-- Error Message -->
    <div v-if="errorMessage" class="error-message">
      <div class="error-icon">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
          <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
        </svg>
      </div>
      <div class="error-content">
        <span class="error-title">出现错误</span>
        <p class="error-details">{{ errorMessage }}</p>
      </div>
      <button class="error-close" @click="errorMessage = null">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
          <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
        </svg>
      </button>
    </div>

    <!-- File List -->
    <div class="file-container">
      <div v-if="!errorMessage && directoryContents.length === 0 && currentPath" class="empty-state">
        <div class="empty-icon">📂</div>
        <h3>目录为空</h3>
        <p>此目录中没有文件或文件夹</p>
      </div>
      
      <div v-else class="file-grid">
        <div 
          v-for="entry in directoryContents" 
          :key="entry.name" 
          @click="navigateTo(entry)" 
          :class="['file-item', { directory: entry.is_directory, file: !entry.is_directory }]"
        >
          <div class="file-icon">
            {{ getFileIcon(entry) }}
          </div>
          <div class="file-info">
            <div class="file-name">{{ entry.name }}</div>
            <div class="file-type">{{ getFileType(entry) }}</div>
          </div>
          <div class="file-actions">
            <button class="action-btn" @click.stop="() => {}">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
}

/* Header Styles */
.app-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 1rem 2rem;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.logo-icon {
  font-size: 2rem;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-10px); }
}

h1 {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.breadcrumb {
  font-size: 0.9rem;
  color: #666;
  background: #f8f9fa;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-family: 'Courier New', monospace;
}

/* Navigation Styles */
.nav-bar {
  background: rgba(255, 255, 255, 0.9);
  padding: 1.5rem 2rem;
  display: flex;
  gap: 2rem;
  flex-wrap: wrap;
  align-items: center;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.path-form, .create-form {
  display: flex;
  gap: 0.75rem;
  align-items: center;
}

.path-input-container, .create-input-container {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.nav-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.25rem;
  border: none;
  border-radius: 10px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9rem;
}

.up-btn {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
}

.up-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(238, 90, 82, 0.4);
}

.up-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.browse-btn {
  background: linear-gradient(135deg, #4ecdc4, #44a08d);
  color: white;
}

.browse-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(68, 160, 141, 0.4);
}

.create-btn {
  background: linear-gradient(135deg, #feca57, #ff9ff3);
  color: white;
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(254, 202, 87, 0.4);
}

#path-input, #new-folder-input {
  padding: 0.75rem 1rem;
  border: 2px solid #e9ecef;
  border-radius: 10px;
  font-size: 0.9rem;
  width: 300px;
  transition: all 0.3s ease;
  background: white;
}

#path-input:focus, #new-folder-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
}

/* Error Message Styles */
.error-message {
  display: flex;
  align-items: center;
  gap: 1rem;
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  padding: 1rem 2rem;
  margin: 1rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(238, 90, 82, 0.3);
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from { transform: translateX(-100%); opacity: 0; }
  to { transform: translateX(0); opacity: 1; }
}

.error-icon {
  flex-shrink: 0;
}

.error-content {
  flex-grow: 1;
}

.error-title {
  font-weight: 700;
  font-size: 1.1rem;
  display: block;
  margin-bottom: 0.25rem;
}

.error-details {
  margin: 0;
  opacity: 0.9;
  font-size: 0.9rem;
}

.error-close {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  padding: 0.5rem;
  border-radius: 50%;
  cursor: pointer;
  transition: background 0.3s ease;
}

.error-close:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* File Container Styles */
.file-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.7;
}

.empty-state h3 {
  margin: 0 0 0.5rem 0;
  color: #333;
  font-size: 1.5rem;
}

.empty-state p {
  margin: 0;
  color: #666;
  font-size: 1rem;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.file-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 1.5rem;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.5);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  gap: 1rem;
  position: relative;
  overflow: hidden;
}

.file-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.file-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.file-item:hover::before {
  transform: scaleX(1);
}

.file-item.directory {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
}

.file-icon {
  font-size: 2.5rem;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.file-item:hover .file-icon {
  transform: scale(1.1);
}

.file-info {
  flex-grow: 1;
  min-width: 0;
}

.file-name {
  font-weight: 600;
  font-size: 1rem;
  color: #333;
  margin-bottom: 0.25rem;
  word-break: break-word;
  line-height: 1.3;
}

.file-type {
  font-size: 0.85rem;
  color: #666;
  opacity: 0.8;
}

.file-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
}

.file-item:hover .file-actions {
  opacity: 1;
}

.action-btn {
  background: rgba(102, 126, 234, 0.1);
  border: none;
  padding: 0.5rem;
  border-radius: 8px;
  cursor: pointer;
  color: #667eea;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: rgba(102, 126, 234, 0.2);
  transform: scale(1.1);
}

/* Responsive Design */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .nav-bar {
    flex-direction: column;
    gap: 1rem;
  }
  
  #path-input, #new-folder-input {
    width: 100%;
    max-width: 300px;
  }
  
  .file-grid {
    grid-template-columns: 1fr;
  }
  
  .file-container {
    padding: 1rem;
  }
}
</style>

<style>
/* Global styles */
:root {
  font-family: 'Inter', 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 16px;
  line-height: 1.6;
  font-weight: 400;
  color: #333;
  background: #f8f9fa;
  font-synthesis: none;
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-text-size-adjust: 100%;
}

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
}

@media (prefers-color-scheme: dark) {
  .container {
    background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
  }
  
  .app-header {
    background: rgba(44, 62, 80, 0.95);
    color: #ecf0f1;
  }
  
  h1 {
    background: linear-gradient(135deg, #74b9ff, #0984e3);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }
  
  .breadcrumb {
    background: rgba(52, 73, 94, 0.8);
    color: #bdc3c7;
  }
  
  .nav-bar {
    background: rgba(44, 62, 80, 0.9);
  }
  
  #path-input, #new-folder-input {
    background: rgba(52, 73, 94, 0.8);
    color: #ecf0f1;
    border-color: #555;
  }
  
  #path-input:focus, #new-folder-input:focus {
    border-color: #74b9ff;
    box-shadow: 0 0 0 3px rgba(116, 185, 255, 0.1);
  }
  
  .file-item {
    background: rgba(44, 62, 80, 0.9);
    border-color: rgba(116, 185, 255, 0.2);
  }
  
  .file-item.directory {
    background: linear-gradient(135deg, rgba(116, 185, 255, 0.1), rgba(9, 132, 227, 0.1));
  }
  
  .file-name {
    color: #ecf0f1;
  }
  
  .file-type {
    color: #bdc3c7;
  }
  
  .file-icon {
    background: rgba(116, 185, 255, 0.1);
  }
  
  .action-btn {
    background: rgba(116, 185, 255, 0.1);
    color: #74b9ff;
  }
  
  .action-btn:hover {
    background: rgba(116, 185, 255, 0.2);
  }
  
  .empty-state {
    background: rgba(44, 62, 80, 0.9);
    color: #ecf0f1;
  }
  
  .empty-state h3 {
    color: #ecf0f1;
  }
  
  .empty-state p {
    color: #bdc3c7;
  }
}
</style>
